//
//  CXHttpTool.swift
//  CXSwiftDemo
//
//  Created by 潮汐 on 2023/12/6.
//
//网路请求封装

import UIKit

////导入网路请求框架
import Alamofire
////JSON数据处理
//import SwiftyJSON

class CXHttpTool {
    //请求头
    lazy var myHeaders: HTTPHeaders = []
    
    //单例代替（dispatch_once在Swift中已被废弃）
    static let sharedManager = CXHttpTool()
    init() {
        //在这里做事，只会执行一次
        
        //HTTPHeaders 设置请求头
        myHeaders =  [
            "Conatent-Type": "application/json",
            "Accept": "application/json"
        ]
    }
    
    
    //用static或者class关键字定义（对应OC里的类方法+）
    
    /// post网络请求封装
    /// - Parameters:
    ///   - path: 接口地址
    ///   - para: 请求参数
    ///   - show: 是否显示遮罩
    ///   - showMsg: 是否弹窗显示错误信息
    ///   - SuccessBlock: 成功回调
    ///   - FailureBlock: 失败回调
    static func postWithURL(PathUrl path: String, Parameters para: [String: Any]?, ShowHUD show:Bool, ShowErrorMsg showMsg:Bool, SuccessBlock: @escaping (_ isSuccess: Bool, _ responseDict:Dictionary<String, Any>) -> Void ,FailureBlock: @escaping (_ error: Error?) -> Void) {//@escaping逃逸闭包
        
        //发起网络请求
        AF.request(path,//接口名
                   method: .get,//请求方式
                   parameters: para,//请求参数
                   headers: CXHttpTool.sharedManager.myHeaders//HTTP Headers 请求头设置
        ).responseString { responseMy in //请求结果解析为String
//            debugPrint("网络请求结果：\(responseMy)")//打印
            switch responseMy.result {
            case let .success(responseString)://网络请求成功数据：json字符串
                let pathHttp: String = responseMy.request?.description ?? ""
                print("接口：\(pathHttp)")
//                {"weatherinfo":{"SD":"86%","WD":"西风","WS":"3级","WSE":"","city":"","cityid":"101040100","isRadar":"1","radar":"JC_RADAR_AZ9010_JB","temp":"15","time":"22:45","weather":"多云"}}
                print("网络请求成功string：\(responseString)")
                
                //这种转化方式也可以
//                let json = JSON(parseJSON: responseString)
                
                //json字符串转字典
                if let data = responseString.data(using: .utf8) {//字符串转Data
                    let json = try? JSON(data: data)//SwiftyJSON来做json字符串转字典 //加try，转化成功返回数据，失败返回nil
                    if let responseDictMy = json?.dictionaryObject {
                        //转换成功
                        print("网络请求数据（json转字典）：\(responseDictMy)")
                        //成功
                        SuccessBlock(true, responseDictMy)//
                        
                    }else {
                        //业务数据失败
                        SuccessBlock(false, [:])//
                    }
                }else {
                    //业务数据失败
                    SuccessBlock(false, [:])//
                }
            
            case let .failure(error):
                
                print("网络请求失败：\(error)")
                //失败
                FailureBlock(error)
            }
        }
    }
}
